<template>
  <view class="page">
    <view class="card">
      <view class="card_row">
        <view class="title text-nowarp"> 头像 </view>
        <view class="margin-top-" @longtap="previewImage">
          <!-- <button
            class="u-reset-button user-btn-img"
            :data-eventsync="true"
            @tap="useChooseavatar"
            @longtap="previewImage"
          ></button>
          <up-image
            :src="$data.userHead"
            shape="circle"
            width="100rpx"
            height="100rpx"
            @click="useChooseavatar"
          ></up-image> -->
          <up-image
            :src="$data.userHead"
            shape="circle"
            width="100rpx"
            height="100rpx"
          ></up-image>
        </view>
      </view>
      <view class="card_row">
        <view class="title margin-top text-nowarp">昵称</view>
        <view class="row">
          <input
            v-model="params.nickname"
            placeholder="请输入用户昵称"
            class="text-right"
            @change="getNickName"
          />
          <view> {{}} </view>
        </view>
      </view>
      <view class="card_row">
        <view class="title text-nowarp">性别</view>
        <view class="row">
          <radio-group
            :value="params.sex"
            class="flex"
            @change="activityTypeChange"
          >
            <label class="flex align-center">
              <view>
                <radio
                  :value="1"
                  :checked="params.sex == 1"
                  style="transform: scale(0.7)"
                />
              </view>
              <view>男</view>
            </label>
            <label class="flex align-center margin-left">
              <view>
                <radio
                  :value="2"
                  :checked="params.sex == 2"
                  style="transform: scale(0.7)"
                />
              </view>
              <view>女</view>
            </label>
          </radio-group>
        </view>
      </view>
      <view class="card_row">
        <view class="title margin-top text-nowarp">生日</view>
        <view class="row">
          <up-datetime-picker
            :show="$data.show"
            v-model="params.birthday"
            mode="date"
            :minDate="new Date('1900').getTime()"
            :maxDate="new Date().getTime()"
            @cancel="$data.show = false"
            @confirm="onBirthdayConfirm"
          >
          </up-datetime-picker>
          <view @tap="$data.show = true">
            {{ params.birthday || "请选择生日" }}
          </view>
        </view>
      </view>
      <view
        class="margin-top-xxl text-center text-main-color"
        :data-eventsync="true"
        @tap="onGetUserInfo"
      >
        点击获取用户信息（昵称，头像等）
      </view>
      <view class="btn margin-top-xl" @tap="onSub">保存</view>
    </view>
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from "vue";
import {
  onLoad,
  onShow,
  onHide,
  onReady,
  onPageScroll,
  onReachBottom,
  onPullDownRefresh,
  onShareAppMessage,
  onShareTimeline,
  onTabItemTap,
} from "@dcloudio/uni-app";
import BasicConfig from "../../utils/config";
import { useGetUserStorage } from "../../hooks/useStorage";
import { IOSDate } from "../../utils/utils";
import test from "../../uni_modules/uview-plus/libs/function/test";
import { useUploadFilePromise } from "../../hooks/useUpload";
import errorCode from "../../utils/http/errorCode";
import { useEditUserInfo, useGetUserInfo } from "../../hooks/useUser";
import { useImgSrc } from "../../hooks/useImg";

const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const userInfo = useGetUserStorage();
const $data = reactive({
  show: false,
  userHead: "", // 用户头像
});
const params = reactive({
  avatar: "",
  nickname: "",
  sex: 1, // 1 男 2 女
  birthday: "",
});
const onBirthdayConfirm = (e) => {
  const time = test.number(e.value)
    ? e.value
    : new Date(IOSDate(e.value)).getTime();
  params.birthday = uni.$u.timeFormat(time, "yyyy-mm-dd");
  $data.show = false;
  console.log("日期", time, e, params.birthday);
};
const onSub = () => {
  if (!params.nickname) {
    BasicConfig.toast("请填写昵称");
    return;
  }
  uni.showModal({
    title: "提示",
    content: "确认提交?",
    success: (success) => {
      if (success.confirm) {
        useEditUserInfo(params).then((res) => {
          BasicConfig.toast(res.msg);
          if (res.code === errorCode.success) {
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          }
        });
      }
    },
  });
};
const getNickName = (e) => {
  params.nickname = e.detail.value;
};
const activityTypeChange = (e) => {
  params.sex = Number(e.detail.value);
};
// 用户头像
const useChooseavatar = (e) => {
  uni.getUserProfile({
    success: (success) => {
      console.log("success", success);
      const userInfo = success.userInfo;
      params.nickname = userInfo.nickName;
      params.sex = userInfo.gender == 0 ? 2 : 1;
      uni.downloadFile({
        url: userInfo.avatarUrl,
        success: (downRes) => {
          console.log("downRes", downRes);
          useUploadFilePromise(downRes.tempFilePath, {
            user: "test",
            key: "file",
          }).then((res) => {
            BasicConfig.toast(res.msg);
            if (
              res.code === errorCode.success &&
              res.data &&
              res.data.length > 0
            ) {
              const response = res.data[0];
              if (response.error === 0) {
                params.avatar = response.url;
                $data.userHead = useImgSrc(response.url);
                console.log("$data.userHead", $data.userHead);
              } else {
                uni.hideToast();
                BasicConfig.toast("上传失败!");
              }
            }
          });
        },
      });
    },
    fail: (fail) => {
      console.log("fail", fail);
    },
  });
};
const previewImage = () => {
  if (!params.avatar) return;
  const url = useImgSrc(params.avatar);
  uni.previewImage({
    urls: [url],
  });
};
const onGetUserInfo = () => {
  useChooseavatar();
};
const init = async () => {
  await useGetUserInfo();
  const userInfo = useGetUserStorage();
  $data.userHead = useImgSrc(userInfo.avatar);
  params.avatar = userInfo.avatar;
  params.nickname = userInfo.nickname;
  params.sex = userInfo.sex;
  params.birthday = userInfo.birthday;
};
onLoad((options) => {
  init();
});
onReady(() => {});
onShareAppMessage(() => {});
onShareTimeline(() => {});
</script>

<style lang="scss" scoped>
.page {
  background: #ffffff;
  width: 100%;
  padding: 30rpx;
  min-height: 100vh;
  .card_row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    padding: 30rpx 0;
    position: relative;
    // margin-bottom: 30rpx;
  }
  .row {
    // padding: 30rpx 0;
    // border-bottom: 1px solid #f0f0f0;
    // margin-bottom: 30rpx;
    .code {
      margin-left: 20rpx;
      .code_sms {
        color: #e4b300;
      }
    }
  }
  .btn {
    background: $main-color;
    border-radius: 100rpx;
    width: 100%;
    padding: 30rpx;
    text-align: center;
    color: #ffffff;
    font-size: 32rpx;
  }
  .user-btn-img {
    width: 100rpx;
    height: 100rpx;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 30rpx;
    margin: auto;
    background: transparent;
    z-index: 9;
    border-radius: 100%;
  }
}
</style>
